package com.ctu.autodial;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.jar.JarOutputStream;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ctu.app.utils.Des;
//import com.ctu.app.utils.LogUtil;
import com.ctu.app.utils.Request;
import com.ctu.app.utils.Response;
import com.ctu.autodial.util.SimulateEvent;

/**
 * 监控通道
 * 
 * @author wxm
 * 
 */
public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";
	private Button setup_autodial = null;// 开始服务
	private EditText telNum = null;// 手机号码
	private EditText serverIp = null;// 服务器ip
	private ScrollView log_scrolView = null;// 多条日志显示
	private TextView log_textview = null;// 单条日志显示
	private TextView log_title = null;// 用于getevent
	private String HOST = "192.168.3.126:6004";// 服务器地址
	private String TestHost = "192.168.3.194:8088";// 测试服务器地址
	private String PHONE = "15221194637";// 本地手机号
	private String log;// 日志信息
	private AutoDialTimerTask mAutoDialTimerTask;
	private UploadStatusTimerTask mUploadStatusTimerTask;// 上传充值状态计时器
	private Timer autoDialTimer;
	private CallPhoneService mCallPhoneService;
	private ServiceConnectionImpl mServiceConnectionImpl;
	private String CMD_CALLGET = "callget";
	private String CMD_CALLSTATUS = "callstatus";
	private String clientTime;
	private final String REQUEST_KEY = "ctu45678";
	private RechargeInfo mRechargeInfo;
	private ReturnCallStatusReceive mReuCallStatusReceive;// 接收充值的状态
	static List<RechargeInfo> rechargeInfoList = new ArrayList<RechargeInfo>();// 共享list集合
	static List<RechargeInfo> rechargeInfoExceptionList = new ArrayList<RechargeInfo>();// 共享list集合
	SharedPreferences preferences;
	boolean uploadStatusCycleFlag = true;// 循环上传充值状态标志
	int localCallStatus;// 当前的充值状态码
	int MAX_TRYUPDATESTATUS_COUNT = 10;// 循环上传充值状态最大值
	public static boolean isEventClicked = false;
	private static final String EXCEPTION_FILE_NAME = "AutoDialRunException";

	// **********测试*******************
	private boolean URL_DEBUG = false;// true：测试
	private boolean EXCEPTION_DEBUG = false;// true:测试异常重启设备
	private boolean CALL_DEBUG = true;// false:关闭拨打充值电话流程
	private String exception;// test for exception
	private final static String TAGE = "xml";

	// ********************************************
	private static Logger runLogger;
	private static SimulateEvent simulateEvent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate--->");
		setContentView(R.layout.autodial_main);
		simulateEvent = new SimulateEvent();
		runLogger = CrashApplication.getLoggerInstance();// 创建日志记录器
		initView();
		mServiceConnectionImpl = new ServiceConnectionImpl();// 接收服务状态
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, CallPhoneService.class);
		getApplicationContext().bindService(intent, mServiceConnectionImpl,
				BIND_AUTO_CREATE);

		mReuCallStatusReceive = new ReturnCallStatusReceive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.ctu.autodial.callstatus");
		registerReceiver(mReuCallStatusReceive, filter);

		simulateEvent.getEventId();// 获取getEvent事件

		initAutoDial();// 开启程序
	}

	/**
	 * 初始化控件
	 */
	private void initView() {

		serverIp = (EditText) findViewById(R.id.server_ip);
		telNum = (EditText) findViewById(R.id.tel_num);
		setup_autodial = (Button) findViewById(R.id.setup_autodial);
		log_scrolView = (ScrollView) findViewById(R.id.log_scrollview);
		log_textview = (TextView) findViewById(R.id.log_textview);
		log_title = (TextView) findViewById(R.id.log_title);

		preferences = this.getPreferences(MODE_PRIVATE);/* 获取配置信息 */
		HOST = preferences.getString("host", HOST);
		PHONE = preferences.getString("phone", PHONE);

		serverIp.setText(HOST);
		telNum.setText(PHONE);

		widgetInvisible();

		setup_autodial.setOnClickListener(new OnClickListenerImpl());
		log_title.setOnClickListener(new OnClickListenerImpl());

	}

	/**
	 * 初始化数据 从share
	 */
	private void initAutoDial() {

		if (autoDialTimer == null) {

			if (EXCEPTION_DEBUG) {
				System.out.println(exception.equals("exceptionStr"));
			}
			startServerListener();// 开启计数器服务
		}
	}

	/**
	 * 设置组件为不可见
	 */
	private void widgetInvisible() {

		telNum.setEnabled(false);
		telNum.setClickable(false);
		serverIp.setClickable(false);
		serverIp.setEnabled(false);
	}

	/**
	 * 使用Timer，执行指定的任务
	 */
	private void startCallServer(String mobile, String pwd) {

		if (CALL_DEBUG) {
			mCallPhoneService.StartCall(mobile, pwd);
		}
	}

	/**
	 * 使用计时器，从服务器获取数据
	 */
	class AutoDialTimerTask extends TimerTask {

		@Override
		public void run() {
			printLog(clientTime + ":" + "轮询从服务器获取手机号和卡密，并拨打充值电话...");

			// LogUtil.saveLog2File("轮询从服务器获取手机号和卡密，并拨打充值电话...");// 保存日志

			runLogger.info("polling mobile&cardpwd from server...");

			getLocalTime();
			SendQuery(CMD_CALLGET, telNum.getText().toString(), clientTime,
					getMD5(CMD_CALLGET + clientTime + REQUEST_KEY),
					queryResponse);

		}
	}

	/**
	 * 使用Timer，执行指定的任务
	 */
	private void startServerListener() {
		stopServerListener();
		Log.d(TAG, "start timer...");
		autoDialTimer = new Timer();
		mAutoDialTimerTask = new AutoDialTimerTask();
		autoDialTimer.schedule(mAutoDialTimerTask, 0, 30 * 1000);
	}

	/**
	 * 监听停止服务
	 */
	void stopServerListener() {

		Log.d(TAG, "stop timer...");
		if (mAutoDialTimerTask != null) {
			mAutoDialTimerTask.cancel();
			mAutoDialTimerTask = null;
		}

		if (autoDialTimer != null) {
			autoDialTimer.cancel();
			autoDialTimer = null;
		}
	}

	/**
	 * 用于管理监听，开始服务监听器
	 * 
	 * 响应点击事件，获取view中的值，并对其进行修改
	 * 
	 * @author wxm
	 * 
	 */
	class OnClickListenerImpl implements View.OnClickListener {

		@Override
		public void onClick(View view) {
			switch (view.getId()) {

			case R.id.setup_autodial:
				String status = setup_autodial.getText().toString();
				if (status.equals("设置")) {// 保存配置信息并开启程序
					stopServerListener();
					setup_autodial.setClickable(true);
					telNum.setClickable(true);
					serverIp.setClickable(true);
					telNum.setEnabled(true);
					serverIp.setEnabled(true);
					setup_autodial.setText("启动");

				} else {
					setup_autodial.setText("设置");
					setup_autodial.setClickable(true);
					telNum.setClickable(false);
					serverIp.setClickable(false);
					telNum.setEnabled(false);
					serverIp.setEnabled(false);
					createSP();
					hideSoftInputKeyBoard();

					initAutoDial();
					// startCallServer("13688118774", "013023580578955665");

				}
				break;
			}
		}
	}

	/**
	 * 创建配置文件:保存主机和手机号
	 * 
	 */
	private void createSP() {
		Log.d(TAG, "createSP");
		HOST = serverIp.getText().toString();
		PHONE = telNum.getText().toString();
		// 判断输入框是否为空
		preferences.edit().putString("host", HOST).putString("phone", PHONE)
				.commit();
	}

	/**
	 * //http://localhost:8080/JspDemo/page/voice_outbound.jsp?cmd=callget&
	 * appmobile=18294990524&time=2013-01-08
	 * 04:03:16&md5key=95bc397b9ea9032fd8683ed0efd86e18
	 * 
	 * 
	 * @param appmobile
	 * @param time
	 * @param md5key
	 * @param ret
	 */
	void SendQuery(String cmd, String appmobile, String time, String md5key,
			Response ret) {
		Request req = new Request(MainActivity.this);
		String timeLocal = URLEncoder.encode(time);// 格式化

		String url;
		if (URL_DEBUG) {// 测试

			url = "http://" + TestHost
					+ "/JspDemo/page/voice_outbound_test.jsp?cmd=" + cmd
					+ "&appmobile=" + appmobile + "&time=" + timeLocal
					+ "&md5key=" + md5key;
		} else {
			url = "http://" + serverIp.getText().toString()
					+ "/speech.aspx?cmd=" + cmd + "&appmobile=" + appmobile
					+ "&time=" + timeLocal + "&md5key=" + md5key;
		}

		runLogger.info("请求的数据: " + url);// 保存日志
		// LogUtil.saveLog2File("请求的数据: " + url);// 保存日志
		req.Send(url, null, ret);

	}

	/**
	 * //www.xxx.com/speech.aspx?cmd=callstatus&linkid=xxx&status=xxx&msgid=xxx&
	 * appmobile=xxx&mobile=xxx&time=xxx&md5key=xxx
	 * 
	 * @param linkid
	 * @param status
	 * @param msgid
	 * @param appmobile
	 * @param mobile
	 * @param time
	 * @param md5key
	 */
	private void SendReturnCallstatus(String cmd, String linkid, int status,
			long msgid, String appmobile, String mobile, String time,
			String md5key, Response ret) {
		Request req = new Request(MainActivity.this);
		String timeLocal = URLEncoder.encode(time);// 格式化
		String url;

		if (URL_DEBUG) {// 测试
			url = "http://" + TestHost
					+ "/JspDemo/page/voice_outbound_test.jsp?cmd=" + cmd
					+ "&linkid=" + linkid + "&status=" + status + "&msgid="
					+ msgid + "&appmobile=" + appmobile + "&mobile=" + mobile
					+ "&time=" + timeLocal + "&md5key=" + md5key;
		} else {
			url = "http://" + serverIp.getText().toString()
					+ "/speech.aspx?cmd=" + cmd + "&linkid=" + linkid
					+ "&status=" + status + "&msgid=" + msgid + "&appmobile="
					+ appmobile + "&mobile=" + mobile + "&time=" + timeLocal
					+ "&md5key=" + md5key;
		}

		runLogger.info("返回的数据： " + url);// 保存日志
		// LogUtil.saveLog2File("返回的数据： " + url);// 保存日志
		req.Send(url, null, ret);
	}

	/**
	 * 解析卡密 String cipherText = "3D7595A98BFF809D3D0F93F86E85613B";// 密文 3D 75
	 * 95 A9 8B FF 80 9D 3D 0F 93 F8 6E 85 61 3B
	 */
	private String parseDES(String cardpwd) {
		final String DES_KEY = "12ctu3ap";
		String cardpwd_parse = "";

		try {
			cardpwd_parse = Des.decrypt(cardpwd, DES_KEY);
		} catch (Exception e) {
			e.printStackTrace();
			runLogger.error("error to parse des" + e, e);
			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
		}
		return cardpwd_parse;

	}

	/**
	 * 获取当前时间，接口时间
	 * 
	 * 2014-01-01 01:00:00 24小时
	 */
	private void getLocalTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now = new Date();
		clientTime = format.format(now);

	}

	/**
	 * 获取md5
	 * 
	 * @param string
	 *            (cmd+Time+key)
	 * 
	 *            //cmd = callget //Time = getLocalTime() //key = "12345678"
	 */
	public static String getMD5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString().toLowerCase();
	}

	/**
	 * 查询响应
	 */
	Response queryResponse = new Response() {

		@Override
		public void Ret(int code, InputStream is) {
			if (code == 200) {
				if (is == null) {
					printLog(clientTime + ":" + "服务器返回消息为空！");
					return;
				}
				try {
					String jsonStr = Request.inputStream2String(is);
					JSONObject jsonObject = new JSONObject(jsonStr);//
					String jsonCode = jsonObject.getString("code");

					if (!jsonCode.equals("0")) {
						printLog(clientTime + ":" + "服务器返回未知状态值：" + jsonCode);
						runLogger.info("receive unknown value from server："
								+ jsonCode);
						// LogUtil.saveLog2File("服务器返回未知状态值：" + jsonCode);
						return;
					}

					JSONArray data = jsonObject.getJSONArray("data");

					if (data != null) {

						runLogger.info("receive data form server  Length: "
								+ data.length());
						// LogUtil.saveLog2File("服务器返回有效数据的长度: " +
						// data.length());
						if (data.length() != 0) {
							stopServerListener();// 停止获取数据

							/* 将数据放到list集合中 */
							for (int i = 0; i < data.length(); i++) {
								JSONObject json = data.getJSONObject(i);

								RechargeInfo Resend = new RechargeInfo();// 手机充值信息

								mRechargeInfo.setLinkid(json
										.getString("linkid"));// 流水号
								mRechargeInfo.setMobile(json
										.getString("mobile"));// 目标手机号
								mRechargeInfo.setCardpwd(json
										.getString("cardpwd"));// 短信内容
								mRechargeInfo.setResend(json
										.getString("resend"));// //重试次数
								mRechargeInfo.setMobilestatus(json
										.getString("mobilestatus"));// 手机号状态
																	// 1.正常
																	// 2.空号

								runLogger
										.info("receive data form server is：linkid："
												+ mRechargeInfo.getLinkid()
												+ ",mobile: "
												+ mRechargeInfo.getMobile()
												+ ",Cardpwd: "
												+ mRechargeInfo.getCardpwd()
												+ ",Mobilestatus: "
												+ mRechargeInfo
														.getMobilestatus()
												+ ",Resend:"
												+ mRechargeInfo.getResend());
								// LogUtil.saveLog2File("从服务器端获取到的充值信息：流水号："
								// + mRechargeInfo.getLinkid()
								// + ",目标手机号: "
								// + mRechargeInfo.getMobile() + ",短信内容: "
								// + mRechargeInfo.getCardpwd()
								// + ",手机号状态: "
								// + mRechargeInfo.getMobilestatus()
								// + ",重试次数:" + mRechargeInfo.getResend());

								// 将数据 保存的xml文件中？？
								rechargeInfoList.add(mRechargeInfo);
							}

							mRechargeInfo = rechargeInfoList.get(0);
							rechargeInfoList.remove(0);
							runLogger.info("get first json data---->"
									+ mRechargeInfo.toString());
							// LogUtil.saveLog2File("获取到json数组的第一组元素---->"
							// + mRechargeInfo.toString());
							/**
							 * 
							 * 手机正在被用于通话，将获取的数据进行缓存
							 */
							if (CallPhoneService.inCall) {
								runLogger
										.info("从服务器获取到充值信息时：手机正在被用于通话，将获取的数据进行缓存");
								// LogUtil.saveLog2File("从服务器获取到充值信息时：手机正在被用于通话，将获取的数据进行缓存");

								SendReturnCallstatus(CMD_CALLSTATUS,
										mRechargeInfo.getLinkid(), 3,
										System.currentTimeMillis(), telNum
												.getText().toString(),
										mRechargeInfo.getMobile(), clientTime,
										getMD5(CMD_CALLSTATUS + clientTime
												+ REQUEST_KEY), backResponse);

								getNextData();

							} else {
								runLogger
										.info("Enter the recharge dialing process---->"
												+ mRechargeInfo.toString());
								// LogUtil.saveLog2File("进入充值拨号流程---->"
								// + mRechargeInfo.toString());
								startCallServer(mRechargeInfo.getMobile(),
										parseDES(mRechargeInfo.getCardpwd()));// 拨打电话
							}

						}

					} else {
						printLog(clientTime + ":" + "服务器返回data为空");
						runLogger.info("receive data form server is null");
						// LogUtil.saveLog2File("服务器返回data为空");
						return;
					}
					Log.d("kaiz", "heartbeat ret ok!");
				} catch (JSONException e) {
					e.printStackTrace();
					runLogger.error(
							"query recharge data from server,CATCH EXCEPTION："
									+ e.getMessage(), e);
					// LogUtil.saveExceptionLog2File(
					// "查询充值信息时，捕获异常：" + e.getMessage(),
					// EXCEPTION_FILE_NAME);
				}

			} else if (code == -1) {
				printLog(clientTime + ":" + "请求数据时：没有检查到可用的网络，请设置后再试");
				runLogger
						.info("return status value ：NO FOUND AVAILABLE NETWORKS");
				// LogUtil.saveLog2File("请求数据时： 没有检查到可用的网络，请设置后再试");
			} else if (code == -2) {
				printLog(clientTime + ":" + "请求数据时：连接服务器超时，请稍后再试");
				runLogger
						.info("return status value：connect server TIME OUT!!!");
				// LogUtil.saveLog2File("请求数据时：连接服务器超时，请稍后再试");

			} else {
				printLog(clientTime + ":" + "请求数据时：网络连接错误，请稍后再试: " + code);
				runLogger.info("return status value：ERROR TO CONNECT: " + code);
				// LogUtil.saveLog2File("请求数据时：网络连接错误，请稍后再试: " + code);
			}

		}

	};

	/**
	 * 向服务器回传数据后的回应
	 * 
	 * { "code":"0" }
	 */
	Response backResponse = new Response() {

		@Override
		public void Ret(int code, InputStream is) {
			if (code == 200) {
				if (is == null) {
					printLog(clientTime + ":" + "autodialsend服务器返回消息为空!");
					runLogger.info("autodialsend server return data is null");
					// LogUtil.saveLog2File("autodialsend服务器返回消息为空");
					return;
				}
				try {
					String jsonStr = Request.inputStream2String(is);
					JSONObject jsonObject = new JSONObject(jsonStr);
					String jsonCode = jsonObject.getString("code");

					if (!jsonCode.equals("0")) {

						printLog(clientTime + ":" + "服务器返回未知状态值: " + jsonCode);

						runLogger
								.info("AutoDialSendServer return unknown status value: "
										+ jsonCode);
						// LogUtil.saveLog2File("autodialsend服务器返回未知状态值: "
						// + jsonCode);
						return;
					}

					printLog(clientTime + ":" + "服务器返回: 成功!");
					runLogger.info("return server: SUCCESS!!!");
					// LogUtil.saveLog2File("服务器返回: 成功!");

					uploadStatusCycleFlag = true;
					retryCount = 0;// 清空

					stopUploadStatusListener();// 停止上传计时器

					getNextData();// 获取下一组数据

				} catch (JSONException e) {
					e.printStackTrace();
					runLogger.error("ERROR TO PARSE JSON...", e);
					// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
				}

			} else if (code == -1) {
				uploadStatusCycleFlag = false;
				startUploadStatusListener();
				printLog(clientTime + ":" + "返回充值状态时： 没有检查到可用的网络，请设置后再试");
				runLogger
						.info("return status value ：NO FOUND AVAILABLE NETWORKS");
				// LogUtil.saveLog2File("返回充值状态时：没有检查到可用的网络，请设置后再试");
			} else if (code == -2) {
				uploadStatusCycleFlag = false;
				startUploadStatusListener();
				printLog(clientTime + ":" + "返回充值状态时：连接服务器超时，请稍后再试");
				runLogger
						.info("return status value：connect server TIME OUT!!!");
				// LogUtil.saveLog2File("返回充值状态时：连接服务器超时，请稍后再试");
			} else {
				uploadStatusCycleFlag = false;
				startUploadStatusListener();
				printLog(clientTime + ":" + "返回充值状态时：网络连接错误，请稍后再试: " + code);
				runLogger.info("return status value：ERROR TO CONNECT: " + code);
				// LogUtil.saveLog2File("返回充值状态时：网络连接错误，请稍后再试: " + code);
			}

		}
	};

	Timer uploadTimer;

	/**
	 * 开启上传充值状态计时器 30秒一次，10次
	 */
	private void startUploadStatusListener() {
		if (uploadTimer == null) {
			stopUploadStatusListener();
			uploadTimer = new Timer();
			mUploadStatusTimerTask = new UploadStatusTimerTask();
			uploadTimer.schedule(mUploadStatusTimerTask, 0, 30 * 1000);
		}
	}

	/**
	 * 关闭上传充值状态计时器
	 */
	void stopUploadStatusListener() {
		if (mUploadStatusTimerTask != null) {
			mUploadStatusTimerTask.cancel();
			mUploadStatusTimerTask = null;
		}

		if (uploadTimer != null) {
			uploadTimer.cancel();
			uploadTimer = null;
		}
	}

	int retryCount = 0;

	class UploadStatusTimerTask extends TimerTask {

		@Override
		public void run() {
			if (!uploadStatusCycleFlag) {
				retryCount++;
				if (retryCount < MAX_TRYUPDATESTATUS_COUNT) {
					SendReturnCallstatus(CMD_CALLSTATUS,
							mRechargeInfo.getLinkid(), localCallStatus,
							System.currentTimeMillis(), telNum.getText()
									.toString(), mRechargeInfo.getMobile(),
							clientTime, getMD5(CMD_CALLSTATUS + clientTime
									+ REQUEST_KEY), backResponse);

					runLogger.info("tryUpdateStatus： " + retryCount);
					// LogUtil.saveLog2File("tryUpdateStatus： " + retryCount);
				} else {// 超出尝试值
					stopUploadStatusListener();
					runLogger
							.info("fail to upload recharge status value，It'll to get next data!!!");
					// LogUtil.saveLog2File("上传充值状态码失败，即将获取下一组数据");

					getNextData();// 获取下一组数据

				}
			}

		}
	}

	/**
	 * 接收service发来的充值的状态，
	 * 
	 * 并将充值的状态值上传给服务器，
	 * 
	 * 开始下一次轮询获取待充值的信息
	 * 
	 */
	class ReturnCallStatusReceive extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent.getAction().equals("com.ctu.autodial.callstatus")) {
				localCallStatus = intent.getIntExtra("status", 0);
				getLocalTime();

				SendReturnCallstatus(CMD_CALLSTATUS, mRechargeInfo.getLinkid(),
						localCallStatus, System.currentTimeMillis(), telNum
								.getText().toString(),
						mRechargeInfo.getMobile(), clientTime,
						getMD5(CMD_CALLSTATUS + clientTime + REQUEST_KEY),
						backResponse);

				printLog(clientTime + ":" + "向服务器返回拨号充值状态" + localCallStatus);

				runLogger.info("upload status value to server: "
						+ localCallStatus);
				// LogUtil.saveLog2File("向服务器返回拨号充值状态: " + localCallStatus);

			}

		}
	}

	/**
	 * 获取下一组数据
	 */
	private void getNextData() {
		if (rechargeInfoList.isEmpty()) {
			startServerListener();
		} else
			isGetJsonData();// 判断是否有数据
	}

	/**
	 * 判断本地是否有可用的json数据
	 * 
	 * 每30秒向服务器发送http请求
	 */
	private void isGetJsonData() {

		mRechargeInfo = rechargeInfoList.get(0);
		runLogger.info("get next json data---->" + mRechargeInfo.toString());
		// LogUtil.saveLog2File("获取到json数组的下一个元素---->" +
		// mRechargeInfo.toString());
		rechargeInfoList.remove(0);

		if (CallPhoneService.inCall) {
			runLogger
					.info("upload status value to server：手机正在被用于通话，将获取的数据进行缓存");
			// LogUtil.saveLog2File("上传充值状态值的时：手机正在被用于通话，将获取的数据进行缓存");

			SendReturnCallstatus(CMD_CALLSTATUS, mRechargeInfo.getLinkid(), 3,
					System.currentTimeMillis(), telNum.getText().toString(),
					mRechargeInfo.getMobile(), clientTime,
					getMD5(CMD_CALLSTATUS + clientTime + REQUEST_KEY),
					backResponse);

			getNextData();

		} else {
			startCallServer(mRechargeInfo.getMobile(),
					parseDES(mRechargeInfo.getCardpwd()));
		}

	}

	/**
	 * activity和service的连接
	 * 
	 * @author wxm
	 * 
	 */
	private class ServiceConnectionImpl implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			runLogger.info("SERVICE IS CONNECTED!!!");
			// LogUtil.saveLog2File("已建立本地服务连接...");

			mCallPhoneService = ((CallPhoneService.CallPhoneServiceBinder) service)
					.getService();
			if (mCallPhoneService != null) {
				Intent i = new Intent();
				i.setClass(MainActivity.this, CallPhoneService.class);
				MainActivity.this.startService(i);

			}

		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			runLogger.info("SERVICE IS UNCONNECTED...");
			// LogUtil.saveLog2File("服务连接已断开...");
		}

	}

	/**
	 * 断开服务
	 */
	private void unBindService() {
		if (MainActivity.this.mCallPhoneService != null) {
			MainActivity.this
					.unbindService(MainActivity.this.mServiceConnectionImpl); // 取消Service绑定
			MainActivity.this.mCallPhoneService = null; // 清空标记
		}
	}

	/**
	 * 1、判断日志信息的有效性；
	 * 
	 * 2、使用runOnUiThread立即执行ui改变任务
	 */
	private void printLog(String log) {

		if (!TextUtils.isEmpty(log)) {
			MainActivity.this.log = log;
			MainActivity.this.runOnUiThread(printLogRunnable);
		}

	}

	/**
	 * 用于改变log信息
	 * 
	 * 1、获取之前的信息，使用append追加到信息后面
	 * 
	 * 2、scrollview滑动到最新的一条log
	 */
	Runnable printLogRunnable = new Runnable() {

		@Override
		public void run() {

			String log_old = log_textview.getText().toString();
			log_textview.setText(log_old);
			log_textview.append(log + "\n");
			log_scrolView.post(scrollEndRunnable);

		}
	};

	/**
	 * scrollview滚动，并定位到最新的一条log
	 */
	Runnable scrollEndRunnable = new Runnable() {

		@Override
		public void run() {
			log_scrolView.fullScroll(View.FOCUS_DOWN);
		}
	};

	/**
	 * 为了方便查看日志信息界面，隐藏软键盘 获取焦点view，并将其隐藏
	 */
	private void hideSoftInputKeyBoard() {
		View curFocus = getCurrentFocus();
		if (curFocus != null) {
			IBinder token = curFocus.getWindowToken();
			if (token != null) {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(token,
								InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i(TAG, "onStart--->");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i(TAG, "onRestart--->");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "onResume--->");

	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.i(TAG, "onPause--->");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i(TAG, "onStop--->");

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReuCallStatusReceive);
		// unBindService();
	}

}
